<template>
	<div class="mc-relation-formattr">
		<template v-if="!isDetail">
			<Input
				v-if="isStorage === 1"
				v-model="innerValue"
				placeholder="用于展示关联表单的属性，且数据不会保存"
				readonly
			>
				<template
					v-if="relationFieldShowDialog"
					#suffix
				>
					<i
						class="el-icon-search"
						@click="selectForm"
					/>
				</template>
			</Input>
			<Input
				v-else-if="isStorage === 2"
				v-model="innerValue"
				placeholder="用于展示关联表单的属性，且数据同时会保存入库"
				@input="$emit('input',innerValue)"
			>
				<template
					v-if="relationFieldShowDialog"
					#suffix
				>
					<i
						class="el-icon-search"
						@click="selectForm"
					/>
				</template>
			</Input>
		</template>
		<p v-else>{{innerValue}}</p>
		<RelationForm
			v-if="showRelationForm"
			ref="relationForm"
			:show-input="false"
			v-bind="relationFormProps"
			@change="relationFormChange"
		/>
	</div>
</template>

<script>
import {EventBus} from '../../utils';
import {Input} from 'element-ui';
import RelationForm from '../relation-form';
export default {
	name:'McRelationFormattr',
	components:{
		Input,
		RelationForm,
	},
	model:{
		prop:'value',
		event:'input',
	},
	props:['value', 'showField', 'relationField', 'isDetail', 'isStorage', 'defaultValue', 'readonly', 'relationFieldShowDialog', 'drawingList'],
	data(){
		return {
			innerValue:this.value,
			relationFormProps:{},
			showRelationForm:false,
		};
	},
	watch:{
		value(newVal){
			this.innerValue = newVal;
		},
	},
	mounted(){
		this.getRelationFormInfo();
		EventBus.$on('trigger-relation-formattr', this.handleRelationFormAttr);
	},
	beforeUnmount(){
		EventBus.$off('trigger-relation-formattr', this.handleRelationFormAttr);
	},
	methods:{
		getRelationFormInfo(){
			const findRelationItem = this.drawingList.find((item) => item.model === this.relationField);
			this.relationFormProps = findRelationItem || null;
			this.showRelationForm = Boolean(findRelationItem);
		},
		handleRelationFormAttr(payload){
			if(payload[this.relationField] && payload[this.relationField][this.showField]){
				this.innerValue = payload[this.relationField][this.showField];
			}
			if(this.isStorage === 2){
				this.$emit('input', this.innerValue);
			}
		},
		relationFormChange(val, row){
			if(!this.relationFieldShowDialog) return;
			this.innerValue = row[this.showField];
			if(this.isStorage === 2){
				this.$emit('input', row[this.showField]);
			}
		},
		selectForm(){
			this.$refs.relationForm.visible = true;
		},
	},
};
</script>